package org.hh.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import lombok.SneakyThrows;

public class StudentServer {

    String ip;

    public StudentServer(String ip) {
        this.ip = ip;
    }

    /**
     * 启动学生端服务
     */
    public void startClientServer(){
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap
                .group(workerGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new ObjectEncoder());
                        pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                        pipeline.addLast(new StudentServerHandler());
                    }
                });
        ChannelFuture future = bootstrap.connect(ip, 8888);
        Channel channel = future.channel();
        StudentModel.getInstance().setServerchannel(channel);
        show();
    }

    @SneakyThrows
    private void show(){
        Stage primaryStage = StudentModel.getInstance().getPrimaryStage();
        Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("fxml/server.fxml"));
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                primaryStage.setScene(new Scene(root));
            }
        });
    }
}
